﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

namespace XWeb
{
    public partial class GetImages : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string strMethod = Request.Form["azku"] ?? Request.QueryString["azku"] ?? "";
            switch (strMethod)
            {
                case "GetImageList":
                    GetImageList();
                    break;
            }
        }

        public void GetImageList()
        {
            List<string> demoimagepath = new List<string> { GetImagePath("Resources/1/mm1_01.jpg"), GetImagePath("Resources/1/mm1_02.jpg") };
            byte[] buffer = this.GetImagesBuffer(demoimagepath);
            string strwrite = Convert.ToBase64String(buffer);
            if (buffer == null) return;
            Response.Clear();
            Response.AddHeader("Content-Type", "application/octet-stream;Charset=utf-8;");
            Response.AddHeader("Content-Length", strwrite.Length.ToString());
            Response.Write(strwrite);
            HttpContext.Current.ApplicationInstance.CompleteRequest();
        }

        private string GetImagePath(string imgAbsPath)
        {
            return System.IO.Path.Combine(HttpRuntime.AppDomainAppPath, imgAbsPath);
        }

        private byte[] GetImagesBuffer(List<string> imagepaths)
        {
            byte[] buffer = null;
            List<byte[]> itemlist = new List<byte[]>();
            int alllength = 0;
            foreach (string it in imagepaths)
            {
                try
                {
                    using (FileStream fs = File.OpenRead(it))
                    {
                        byte[] headbuffer = BitConverter.GetBytes(fs.Length);
                        byte[] bodybuffer = new byte[fs.Length];
                        fs.Read(bodybuffer, 0, bodybuffer.Length);
                        byte[] itembuffer = new byte[headbuffer.Length + bodybuffer.Length];
                        headbuffer.CopyTo(itembuffer, 0);
                        bodybuffer.CopyTo(itembuffer, headbuffer.Length);
                        itemlist.Add(itembuffer);
                        alllength += itembuffer.Length;
                    }
                }
                catch
                {
                }
            }
            if (alllength > 0)
            {
                buffer = new byte[alllength];
                int irank = 0;
                foreach (var it in itemlist)
                {
                    it.CopyTo(buffer, irank);
                    irank += it.Length;
                }
            }
            return buffer;
        }
    }
}